import { computed, ref, watch } from 'vue'
import { dataPick } from '@/utils/util.js'

export default function useForm(columns, slot, formOtherColumns) {
  // 查询参数
  const queryParams = ref({})
  // 查询表单columns
  const queryColumns = ref([])
  // 查询表单插槽keys集合
  const querySlotKeys = ref([])

  const isQueryFilter = computed(() => {
    return queryColumns.value.length > 0
  })
  watch(
    () => columns,
    () => {
      const params = {}
      let newColumns = []
      const slotKeys = []

      const formColumns = [...columns, ...formOtherColumns]

      if (!slot.form) {
        // 不使用了表单插槽 才需要设置 设置查询参数 和 设置查询columns
        for (const { prop, label, slotName, search, initialValue } of formColumns) {
          // 表示当前列需要查询
          if (search) {
            const propName = prop ?? slotName
            // 设置查询参数 如果时多选 是否为数组呢？？
            params[propName] = initialValue !== undefined ? initialValue : ''
            // 设置查询columns
            newColumns.push({
              label,
              prop: propName,
              formValueProps: { ...search },
            })
          }
        }
      }

      newColumns = newColumns.sort((a, b) => a.formValueProps.order - b.formValueProps.order)

      // 设置查询插槽keys集合
      for (const { search } of formColumns) {
        if (search) {
          // 设置查询插槽keys集合
          if (search.slots && typeof search.slots === 'object') {
            Object.keys(search.slots).forEach((slotName) => {
              const slotValue = search.slots[slotName]
              if (typeof slotValue === 'string') {
                slotKeys.push(slotValue)
              }
            })
          }
          if (search.render && typeof search.render === 'string') {
            slotKeys.push(search.render)
          }
        }
      }

      queryParams.value = params
      queryColumns.value = newColumns
      querySlotKeys.value = slotKeys
    },
    {
      immediate: true,
    },
  )

  // 表格列插槽
  const formSlots = computed(() => {
    if (querySlotKeys.value && querySlotKeys.value.length > 0) {
      return dataPick(querySlotKeys.value, slot)
    }
    return {}
  })

  return {
    queryParams,
    queryColumns,
    querySlotKeys,
    isQueryFilter,
    formSlots,
  }
}
